<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-10-15
 * Time: 22:43
 *
 */

namespace app\api\controller;
use app\common\controller\ApiController;
use think\Db;
class houses extends ApiController
{

    function __construct(){
        parent::__construct();
    }

    // 房屋列表
    public function housesList() {
        $param = $this->request->param();
        $where[] = ['bd.pms_ar_id','=',$this->userinfo['pms_ar_id']];
        $where[] = ['h.is_deleted','=',0];
        if(!empty($param['building_id'])){
            $where[] = ['b.id','=',$param['building_id']];
        }
        if(!empty($param['name'])) $where[] = ['h.name','like','%'.$param['name'].'%'];
        if(!empty($param['bd_info_id'])) $where[] = ['bd.id','=',$param['bd_info_id']];
        if(!empty($this->userinfo['cm_message_id'])){
            if (@$param['cm_message_id']) {
                $where[] = ['bd.id','in',$param['cm_message_id']];
            } else {
                $where[] = ['bd.id','in',$this->userinfo['cm_message_id']];
            }
        }
        $list = Db::name('wy_houses h')
            ->join('wy_bd_info bd','h.bd_info_id = bd.id')
            ->join('wy_building b','h.building_id = b.id')
            ->join('wy_unit u','h.unit_id = u.id')
            ->where($where)
            ->field('h.id,h.bd_info_id,h.ratio,h.num,bd.name bd_info_name,b.name building_name,u.name unit_name,h.floor,h.name houses_name,h.area,h.houses_type,h.weights')
            ->page($param['pageNo'],$param['pageSize'])
            ->order('h.id','desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['bz_number'] = Db::name('wy_toll_bz_middle')->alias('m')
                ->join('wy_toll_project p','m.project_id = p.id')
                ->join('wy_toll_project_detial d','m.project_detail_id = d.id')
                ->where(['houses_id'=>$v['id'],'type'=>1])->count();
            $list[$k]['houses_type_text'] = getHousesType($v['houses_type']);
        }
        $count = Db::name('wy_houses h')
            ->join('wy_bd_info bd','h.bd_info_id = bd.id')
            ->join('wy_building b','h.building_id = b.id')
            ->join('wy_unit u','h.unit_id = u.id')
            ->where($where)->count();
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>$param['pageNo'],'totalCount'=>$count,'totalPage'=>ceil($count / $param['pageSize'])]);
    }

    // 添加or编辑房屋
    public function operation() {
        $param = $this->request->param();
        unset($param['token']);
        if($param['send'] === 'first'){
            if(empty($param['bd_building_unit'])) return __error('所属小区/楼宇/单元不可为空');
            if(empty($param['floor'])) return __error('所在楼层不可为空');
            if(empty($param['name'])) return __error('房号不可为空');
            if(empty($param['area'])) return __error('房屋面积不可为空');
            if(count($param['bd_building_unit'])!==3){
                return __error('请选择小区');
            }
            list($bd_info_id,$building_id,$unit_id) = $param['bd_building_unit'];
            $param['bd_info_id'] = $bd_info_id;
            $param['building_id'] = $building_id;
            $param['unit_id'] = $unit_id;
            // 查询楼宇信息->判断用户输入是否大于设置的楼层数
            $buildingInfo = Db::name('wy_building')->where('id',$building_id)->find();
            if($param['floor'] > $buildingInfo['layers']) return __error('楼层过大');
            // 查询房屋信息->防止房号重复
            $houseMap[] = ['name','=',$param['name']];
            $houseMap[] = ['unit_id','=',$unit_id];
            $houseMap[] = ['is_deleted','=',0];
            if($param['id'] !== 0) $houseMap[] = ['id','<>',$param['id']];
            $houseInfo = Db::name('wy_houses')->where($houseMap)->find();
            if(!empty($houseInfo)) return __error('房号重复');
        }
        if($param['id'] == 0){
            $id = Db::name('wy_houses')->strict(false)->insert($param,true,true);
            return __success('添加成功',$id);
        }else{
            unset($param['bd_building_unit']);
            unset($param['send']);
            $upRes = Db::name('wy_houses')->update($param);
            return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
        }
    }

    // 删除房屋
    public function delHouses() {
        $ids = $this->request->param('ids');
        if(empty($ids)) return __error('参数错误');
        // 判断当前房屋下是否有住户
//        $user = Db::name('wy_houses_user_middle')->alias('m')->join('wy_houses h','m.houses_id = h.id')->where('m.houses_id','in',$ids)->select();
//        foreach ($user as $key=>$value){
//            return __error('房屋' . $value['name'] . '存在住户,不可删除');
//        }
        $delRes = Db::name('wy_houses_user_middle')->where('houses_id','in',$ids)->delete();
        if(empty($delRes)) return __error('住户解绑失败');
        $upRes = Db::name('wy_houses')->where('id','in',$ids)->update(['is_deleted'=>1]);
        return $upRes !== false ? __success('删除成功') : __error('删除失败');
    }

    // 获取房屋信息
    public function getHousesInfo() {
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $info = Db::name('wy_houses')->where('id',$id)->find();
        $info['time'] = strtotime($info['time']) <= 0 ? null : $info['time'];
        if(!empty($info['imgs'])) {
            $where[] = ['id','in',$info['imgs']];
            $info['imgs'] = model('wy_imgs')->getImgsList($where);
        }else $info['imgs'] = [];
        return __success('ok',$info);
    }

    // 房屋详情
    public function detail() {
        $id = $this->request->param('id');
        $info = Db::name('wy_houses h')
            ->join('wy_bd_info bd','h.bd_info_id = bd.id')
            ->join('wy_building b','h.building_id = b.id')
            ->join('wy_unit u','h.unit_id = u.id')
            ->leftJoin('wy_labels l','h.labels = l.id and l.type_name = 1')
            ->where(['h.id'=>$id,'h.is_deleted'=>0])
            ->field('h.*,bd.name bd_name,num,over_house,is_gt,b.name building_name,u.name unit_name,l.name label_name')->find();
        $info['houses_type_text'] = getHousesType($info['houses_type']);
        $info['time'] = empty($info['time']) ? '' : explode(' ',$info['time'])[0];
        if(!empty($info['imgs'])) {
            $where[] = ['id','in',$info['imgs']];
            $info['imgs'] = model('wy_imgs')->getImgsList($where);
        }else $info['imgs'] = [];
        // 相关住户列表
        $houseUser = Db::name('wy_houses_user_middle')->alias('m')
        ->join('wy_house_user u','m.house_user_id = u.id')
        ->leftJoin('wy_labels l','u.labels_id = l.id')
        ->where(['m.houses_id'=>$info['id']])->field('u.id,u.name,u.phone,l.name label_name,m.type,m.long,m.time')->order('m.id desc')->select();
        foreach ($houseUser as $k=>$v){
             $ht = Db::name('wy_houses_user_middle')->alias('m')
                ->join('wy_house_user u','m.house_user_id = u.id')
                ->join('wy_houses h','m.houses_id = h.id')
                ->join('wy_bd_info bd','h.bd_info_id = bd.id')
                ->join('wy_building b','h.building_id = b.id')
                ->join('wy_unit un','h.unit_id = un.id')
                ->leftJoin('wy_labels l','u.labels_id = l.id')
                ->where('m.house_user_id',$v['id'])->where('m.houses_id','<>',$info['id'])->field('u.id,u.phone,bd.name bd_name,b.name building_name,un.name unit_name,h.name houses_name,l.name label_name,m.type,m.long,m.time')->order('m.id desc')->select();
             if ($ht) {
                 $houseUser[$k]['children'] = $ht;
             }
        }
         // 相关车位
         $houserIdarr=[];
         foreach($houseUser as $K=>$v){
            $houserIdarr[]=$v['id'];
         }
         $carArea=[];
         $car=[];
         if($houserIdarr){
            $carArea = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_car_area c','m.car_area_id = c.id')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where([['m.house_user_id','in',$id],['m.middle_type','=',2]])
            ->field('m.id,m.house_user_id,m.car_area_id,c.name car_area_name,bd.name bd_name,l.name label_name')
            ->select();
        // 相关车辆
            $car = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_car c','m.car_id = c.id')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where([['m.house_user_id','in',$id],['m.middle_type','=',3]])
            ->field('m.id,m.house_user_id,m.car_id,c.name car_name,bd.name bd_name,c.username,c.phone,l.name label_name')
            ->select();
        }
    
        // 相关收费标准
        $tollBz = Db::name('wy_toll_bz_middle')->alias('m')
            ->join('wy_toll_project p','m.project_id = p.id')
            ->join('wy_toll_project_detial d','m.project_detail_id = d.id')
            ->where(['m.houses_id'=>$id,'type'=>1])
            ->field('m.id,p.name project_name,d.name project_detail_name,DATE_FORMAT(m.start_time,"%Y-%m-%d") start_time,DATE_FORMAT(m.end_time,"%Y-%m-%d") end_time,m.is_have_time,m.remarks')->select();
        foreach ($tollBz as $key=>$value){
            if($value['is_have_time'] === 1) $tollBz[$key]['end_time'] = '无结束时间';
        }
        foreach ($houseUser as $key=>$value){
            $houseUser[$key]['bd_name'] = $info['bd_name'];
            $houseUser[$key]['building_name'] = $info['building_name'];
            $houseUser[$key]['unit_name'] = $info['unit_name'];
            $houseUser[$key]['houses_name'] = $info['name'];
            $Household = controller('Household');
            $houseUser[$key]['type_text'] = $Household->getTypeText($value['type']);
            $houseUser[$key]['time_text'] = $value['long'] == 1 ? '长期' : date('Y-m-d',strtotime($value['time']));
            if (@$value['children']) {
                foreach ($value['children'] as $item=>$val){
                    $houseUser[$key]['children'][$item]['type_text'] = $Household->getTypeText($val['type']);
                    $houseUser[$key]['children'][$item]['time_text'] = $val['long'] == 1 ? '长期' : date('Y-m-d',strtotime($val['time']));
                }
            }
        }
        return __success('ok',['info'=>$info,'house_user'=>$houseUser,'bz'=>$tollBz,'carArea'=>$carArea,'car'=>$car]);
    }

    // 删除收费项目
    public function delBz() {
        $id = $this->request->param('id');
        $houses_id = $this->request->param('houses_id');
        $type = $this->request->param('type');
        if(empty($id) || empty($houses_id)) return __error('参数错误');
        $delRes = Db::name('wy_toll_bz_middle')->where(['id'=>$id,'houses_id'=>$houses_id,'type'=>$type])->delete();
        return !empty($delRes) ? __success('删除成功') : __error('删除失败');
    }

    // 绑定用户
    public function bindUser() {
        $param = $this->request->param();
        $type = (int)$this->request->param('m_type');
        $bz = htmlspecialchars($this->request->param('bz'));
        $srr['type'] = $type;
        $srr['note'] = $bz;
        $param['middle_type'] = 1;
        if(!@$param['long'] && !@$param['time']){
            return __error('请选择绑定时间');
        }
        $findIsBind = Db::name('wy_houses_user_middle')->where(['house_user_id'=>$param['house_user_id'],'houses_id'=>$param['houses_id']])->find();
        if(!empty($findIsBind)) return __error('请勿重复绑定');
        $addRes = Db::name('wy_houses_user_middle')->strict(false)->insert($param);
        $modelUsers=model('wy_house_user');
        $userinfos=$modelUsers->where('id',$param['house_user_id'])->find();
        $reg = $userinfos['registry_text'];
        if ($reg == 'excel') {
            $srr['note'] .= '由excel导入';
        }
        $srr['house_user_id'] = (int)$param['house_user_id'];
        $srr['houses_id'] = (int)$param['houses_id'];
        $srr['create_time'] = date('Y-m-d H:i:s');
        Db::name('wy_houses_user_note')->insert($srr);
        if(!$userinfos['houses_id']){
            $houserinfos=model('wy_houses')->find($param['houses_id']);
            $updateArr=[
                'bd_info_id'=>$houserinfos['bd_info_id'],
                'building_id'=>$houserinfos['building_id'],
                'unit_id'=>$houserinfos['unit_id'],
                'houses_id'=>$houserinfos['id'],
                'id'=>$param['house_user_id'],
                'status'=>1,
            ];
            $modelUsers->isUpdate(true)->save($updateArr);
        }
        return $addRes ? __success('绑定成功') : __error('绑定失败');
    }
// 获取收费项目
    public function get_toll_project() {
        $id=$this->request->post('id');
        if(!@$id){
            $type = $this->request->post('type') ?: 0;
            $name = $this->request->post('name') ?: '';
            $where = [];
            if ($type) {
                $where[] = ['project','=',$type];
            }
            if ($name) {
                $where[] = ['name','like','%'.$name.'%'];
            }
            $data = Db::name('wy_toll_project')->where($where)->select();
            if(empty($data)) {
                return __error('暂无数据');
            } else {
                $text = ['1' => '周期性', '2' => '临时性','3' => '押金性','4'=>'优惠规则'];
                foreach($data as $k => $v) {
                    $data[$k]['detail'] = Db::name('wy_toll_project_detial')->where('project_id', $v['id'])->select();
                    if ($v['project'] == 4) {
                        $list  = [
                            '1' => '折扣',
                            '3' => '金额',
                        ];
                    } else {
                        $list  = [
                            '1' => '单价*数量',
                            '2' => '每户单独输入',
                            '3' => '固定金额',
                            '4' => '自定义公式'
                        ];
                    }
                    $data[$k]['project_text'] = $text[$v['project']];
                    foreach($data[$k]['detail'] as $ks => $vs) {

                        if($vs['style'] == '3') {
                            $data[$k]['detail'][$ks]['count_style'] = $list[$vs['style']].':'.$vs['fixed_price'];
                        } else {
                            $data[$k]['detail'][$ks]['count_style'] = $list[$vs['style']];
                        }
                    }
                }
                return __success('查询成功',  $data);
            }
        }else{
            $data=Db::name('wy_toll_project')->where('id',$id)->find();
            return __success('查询成功',  $data);
        }

    }
    public function yh_list(){
        $data = $this->request->post();
//        $pms = $this->userinfo['pms_ar_id'];
//        $q = Db::name('wy_auth')->where('pms_ar_id','in',$pms)->value('menus');
//        $hs = Db::name('wy_web_menu')->where('title','=','优惠权限')->where('id','in',$q)->value('id');
        unset($data['token']);
        $pid = Db::name('wy_toll_project')->where('name','优惠规则')->value('id');
        $list = Db::name('wy_toll_project_detial')->where('project_id',$pid)->select();
        foreach ($list as $k=>$v) {
            if ($v['style'] == 1) {
                $list[$k]['name_s'] = $v['name'].'('.intval($v['price'] * 100).'折)';
            } else {
                $list[$k]['name_s'] = $v['name'].'('.$v['fixed_price'].'元)';
            }
        }
        return __success('ok',$list);
    }
    // 获取可绑定住户
    public function getBindUserList() {
        $id = $this->request->post('id'); // 房屋id
        $bd_info_id = $this->request->post('bd_info_id'); // 小区id
        $text = strFilter($this->request->post('text')); // 搜索
        $type = intval($this->request->post('type'));
        if(empty($text)) return __success('ok',[]);
        if(mb_strlen($text) < 2) return __success('ok',[]);
        // 当前房屋已关联住户
        $middleUser = Db::name('wy_houses_user_middle')->where('houses_id',$id)->column('house_user_id');
        $map = 'status in(1,4)';
        if(!empty($middleUser)){
            $map .= ' and id not in ('.implode(',',$middleUser).')';
        }
        if ($text) {
            if ($type == 1) {
                $map .= ' and (license like \''.$text.'%\')';
            } else {
                $hids = Db::name('wy_houses')->where('name','like','%'.$text.'%')->column('id');
                if ($hids) {
                    $map .= ' and (license like \''.$text.'%\' or name like \''.$text.'%\' or houses_id in ('.implode(',',$hids).'))';
                } else {
                    $map .= ' and (license like \''.$text.'%\' or name like \''.$text.'%\' )';
                }
            }
        }
        $list = Db::name('wy_house_user')->where($map)->field('id value,bd_info_id,building_id,houses_id,name,phone,status')->group('phone')->limit(20)->order('houses_id desc')->select();
        foreach ($list as $key=>$value){
            $bd_info_text = Db::name('wy_bd_info')->where('id',$value['bd_info_id'])->value('name');
            // $building_text = Db::name('wy_building')->where('id',$value['building_id'])->value('name');
            $houses_text = Db::name('wy_houses')->where('id',$value['houses_id'])->value('name');
            if ($value['status'] == 4) {
                $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
            } else {
                if($bd_info_text && $houses_text){
                    $list[$key]['label'] =  $bd_info_text.'-'.$houses_text.'-'.$value['name'].'-'.$value['phone'];
                }else{
                    $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
                }
            }
        }
        return __success('ok',$list);
    }

    // 解绑用户
    public function untied() {
        $houses_id = $this->request->param('houses_id');
        $house_user_id = $this->request->param('house_user_id');
        if(empty($houses_id)) return __error('参数错误');
        if(empty($house_user_id)) return __error('参数错误');
        $delRes = Db::name('wy_houses_user_middle')->where(['houses_id'=>$houses_id,'house_user_id'=>$house_user_id])->delete();
        return !empty($delRes) ? __success('解绑成功') : __error('解绑失败');
    }

    // 获取收费标准
    public function getTollProject() {
        $id = $this->request->post('id');
        $tollProject = Db::name('wy_toll_project')->where('project',1)->field('id value,name label,money_type')->select();
        $tollProjectIds = array();
        foreach ($tollProject as $key=>$value) array_push($tollProjectIds,$value['value']);
        $tollProjectDetail = Db::name('wy_toll_project_detial')->where('project_id','in',$tollProjectIds)->select();
        foreach ($tollProject as $key => $value){
            $tollProject[$key]['key'] = 'p_' . $value['value'];
            $tollProject[$key]['children'] = array();
            foreach ($tollProjectDetail as $tk=>$tv){
                if($tv['project_id'] == $value['value']){
                    $styleList  = ['1' => '单价*数量', '2' => '每户单独输入', '3' => '固定金额', '4' => '自定义公式'];
                    $countStyleList = ['0'=>'未知','1'=>'房屋建筑面积（平米）','2'=>'房屋套内面积（平米）','3'=>'房屋公摊面积（平米）','4'=>'用量（止度-起度）','5'=>'车位面积（平米）','6'=>'车辆排量'];
                    $text = ['1' => '元','2'=>'角','3'=>'分'];
                    $data = [];
                    if($tv['style'] == 1){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].',单价：'.$tv['price'].'，数量：'.$countStyleList[$tv['count_style']].'，计量方式：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'）';
                        $data['money'] = $tv['price'];
                    }else if($tv['style'] == 2){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }else if($tv['style'] == 3){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，固定金额：'.$tv['fixed_price'] . '，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = $tv['fixed_price'];
                    }else if($tv['style'] == 4){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }
                    $data['value'] = $tv['id'];
                    $data['style'] = $tv['style'];
                    array_push($tollProject[$key]['children'],$data);
                }
            }
        }
        if ($id) {
            $list = Db::name('wy_toll_bz_middle')->where('houses_id','in',implode(',',$id))->select();
        } else {
            $list = [];
        }
        $styleList  = ['1' => '单价*数量', '2' => '每户单独输入', '3' => '固定金额', '4' => '自定义公式'];
        $countStyleList = ['0'=>'未知','1'=>'房屋建筑面积（平米）','2'=>'房屋套内面积（平米）','3'=>'房屋公摊面积（平米）','4'=>'用量（止度-起度）','5'=>'车位面积（平米）','6'=>'车辆排量'];
        $text = ['1' => '元','2'=>'角','3'=>'分'];
        foreach ($list as $k=>$v) {
            $pjt = Db::name('wy_toll_project')->where('id',$v['project_id'])->value('money_type');
            $pjt_det = Db::name('wy_toll_project_detial')->where('id',$v['project_detail_id'])->find();
            if($pjt_det['style'] == 1){
                $list[$k]['name'] = $pjt_det['name'] . '（'.$styleList[$pjt_det['style']].',单价：'.$pjt_det['price'].'，数量：'.$countStyleList[$pjt_det['count_style']].'，计量方式：'.$text[$pjt].'，周期：'.$pjt_det['count_week'].'）';
            }else if($pjt_det['style'] == 2){
                $list[$k]['name'] = $pjt_det['name'] . '（'.$styleList[$pjt_det['style']].'，计费精度：'.$text[$pjt].'，周期：'.$pjt_det['count_week'].'月）';
            }else if($pjt_det['style'] == 3){
                $list[$k]['name'] = $pjt_det['name'] . '（'.$styleList[$pjt_det['style']].'，固定金额：'.$pjt_det['fixed_price'] . '，计费精度：'.$text[$pjt].'，周期：'.$pjt_det['count_week'].'月）';
            }else if($pjt_det['style'] == 4){
                $list[$k]['name'] = $pjt_det['name'] . '（'.$styleList[$pjt_det['style']].'，计费精度：'.$text[$pjt].'，周期：'.$pjt_det['count_week'].'月）';
            }
        }
        $rt['rt'] = $tollProject;
        $rt['lit'] = $list;
        return __success('ok',$tollProject);
    }

    // 获取收费标准
    public function getTollProject_ohter($type=1) {
        if($type=1){
            $detailwhere[]=['count_style','in','1,2,3'];
        }elseif ($type=2) {
            $detailwhere[]=['count_style','=','4'];
        }elseif ($type=3) {
            $detailwhere[]=['count_style','=','5'];
        }elseif ($type=4) {
            $detailwhere[]=['count_style','=','6'];
        }elseif ($type=5) {
            $detailwhere[]=['style','=','4'];
        }
        $tollProject = Db::name('wy_toll_project')->where('project',1)->field('id value,name label,money_type')->select();
        $tollProjectIds = array();
        foreach ($tollProject as $key=>$value) array_push($tollProjectIds,$value['value']);
        $tollProjectDetail = Db::name('wy_toll_project_detial')->where($detailwhere)->where('project_id','in',$tollProjectIds)->select();
        foreach ($tollProject as $key => $value){
            $tollProject[$key]['key'] = 'p_' . $value['value'];
            $tollProject[$key]['children'] = array();
            foreach ($tollProjectDetail as $tk=>$tv){
                if($tv['project_id'] == $value['value']){
                    $styleList  = ['1' => '单价*数量', '2' => '每户单独输入', '3' => '固定金额', '4' => '自定义公式'];
                    $countStyleList = ['0'=>'未知','1'=>'房屋建筑面积（平米）','2'=>'房屋套内面积（平米）','3'=>'房屋公摊面积（平米）','4'=>'用量（止度-起度）','5'=>'车位面积（平米）','6'=>'车辆排量'];
                    $text = ['1' => '元','2'=>'角','3'=>'分'];
                    $data = [];
                    if($tv['style'] == 1){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].',单价：'.$tv['price'].'，数量：'.$countStyleList[$tv['count_style']].'，计量方式：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'）';
                        $data['money'] = $tv['price'];
                    }else if($tv['style'] == 2){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }else if($tv['style'] == 3){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，固定金额：'.$tv['fixed_price'] . '，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = $tv['fixed_price'];
                    }else if($tv['style'] == 4){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }
                    $data['value'] = $tv['id'];
                    $data['style'] = $tv['style'];
                    array_push($tollProject[$key]['children'],$data);
                }
            }
        }
        return __success('ok',$tollProject);
    }
    // 获取收费标准
    public function getTollProject_copy() {
        $tollProject1 = $tollProject2= Db::name('wy_toll_project')->where('project',1)->field('id value,name label,money_type')->select();
        $tollProjectIds = array();
        foreach ($tollProject1 as $key=>$value) array_push($tollProjectIds,$value['value']);
        $tollProjectDetail1 = Db::name('wy_toll_project_detial')->where('count_style',4)->where('project_id','in',$tollProjectIds)->select();
        $tollProjectDetail2 = Db::name('wy_toll_project_detial')->where('style','4')->where('project_id','in',$tollProjectIds)->select();
        foreach ($tollProject1 as $key => $value){
            $tollProject1[$key]['key'] = 'p_' . $value['value'];
            $tollProject1[$key]['children'] = array();
            foreach ($tollProjectDetail1 as $tk=>$tv){
                if($tv['project_id'] == $value['value']){
                    $styleList  = ['1' => '单价*数量', '2' => '每户单独输入', '3' => '固定金额', '4' => '自定义公式'];
                    $countStyleList = ['0'=>'未知','1'=>'房屋建筑面积（平米）','2'=>'房屋套内面积（平米）','3'=>'房屋公摊面积（平米）','4'=>'用量（止度-起度）','5'=>'车位面积（平米）','6'=>'车辆排量'];
                    $text = ['1' => '元','2'=>'角','3'=>'分'];
                    $data = [];
                    if($tv['style'] == 1){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].',单价：'.$tv['price'].'，数量：'.$countStyleList[$tv['count_style']].'，计量方式：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'）';
                        $data['money'] = $tv['price'];
                    }else if($tv['style'] == 2){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }else if($tv['style'] == 3){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，固定金额：'.$tv['fixed_price'] . '，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = $tv['fixed_price'];
                    }else if($tv['style'] == 4){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }
                    $data['value'] = $tv['id'];
                    $data['style'] = $tv['style'];
                    array_push($tollProject1[$key]['children'],$data);
                }
            }
        }
        foreach ($tollProject2 as $key => $value){
            $tollProject2[$key]['key'] = 'p_' . $value['value'];
            $tollProject2[$key]['children'] = array();
            foreach ($tollProjectDetail2 as $tk=>$tv){
                if($tv['project_id'] == $value['value']){
                    $styleList  = ['1' => '单价*数量', '2' => '每户单独输入', '3' => '固定金额', '4' => '自定义公式'];
                    $countStyleList = ['0'=>'未知','1'=>'房屋建筑面积（平米）','2'=>'房屋套内面积（平米）','3'=>'房屋公摊面积（平米）','4'=>'用量（止度-起度）','5'=>'车位面积（平米）','6'=>'车辆排量'];
                    $text = ['1' => '元','2'=>'角','3'=>'分'];
                    $data = [];
                    if($tv['style'] == 1){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].',单价：'.$tv['price'].'，数量：'.$countStyleList[$tv['count_style']].'，计量方式：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'）';
                        $data['money'] = $tv['price'];
                    }else if($tv['style'] == 2){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }else if($tv['style'] == 3){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，固定金额：'.$tv['fixed_price'] . '，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = $tv['fixed_price'];
                    }else if($tv['style'] == 4){
                        $data['label'] = $tv['name'] . '（'.$styleList[$tv['style']].'，计费精度：'.$text[$value['money_type']].'，周期：'.$tv['count_week'].'月）';
                        $data['money'] = 0;
                    }
                    $data['value'] = $tv['id'];
                    $data['style'] = $tv['style'];
                    array_push($tollProject2[$key]['children'],$data);
                }
            }
        }
        return __success('ok',['t1'=>$tollProject1,'t2'=>$tollProject2]);
    }
    public function TollProjectAdd(){
        $param = $this->request->post();
        if(!@$param['houses_id']){
            return  __error('未选择房屋/车位/车辆');
        }
        if($param['action']=='add'){
            if(!@$param['infos']){
                return  __error('未选择收费项');
            }
            $saveArr=[];
            foreach($param['houses_id'] as $key=>$value){
                foreach($param['infos'] as $k=>$v){
                    unset($v['name']);
                    if($v['is_have_time']==true){
                        $v['is_have_time']=1;
                    }else {
                        $v['is_have_time']=0;
                    }
                    $v['houses_id']=$value;
                    $saveArr[]=$v;
                }
            }
            $ret=Db::name('wy_toll_bz_middle')->insertAll($saveArr);
            if($ret){
                return __success('ok');
            }else {
                return __error('新增失败');
            }
        }else {
            $where[]=['houses_id','in',$param['houses_id']];
            $ret=Db::name('wy_toll_bz_middle')->where($where)->delete();
            if($ret){
                if(@$param['infos']){
                    $saveArr=[];
                    foreach($param['houses_id'] as $key=>$value){
                        foreach($param['infos'] as $k=>$v){
                            if (!@$v['id']) {
                                unset($v['name']);
                                if($v['is_have_time']==true){
                                    $v['is_have_time']=1;
                                }else {
                                    $v['is_have_time']=0;
                                }
                                $v['houses_id']=$value;
                                $saveArr[]=$v;
                            }
                        }
                    }
                    Db::name('wy_toll_bz_middle')->insertAll($saveArr);
                }
                return __success('ok');
            }else {
                return __error('删除失败');
            }
        }
    }
    // 获取小区楼宇房屋
    public function getCommunityBuildingHouse(){
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        $communityIds = array();
        foreach ($communityList as $key=>$value) {
            array_push($communityIds,$value['value']);
            $communityList[$key]['id']=$value['value'];
        }
        // 楼宇
        $buildingList = Db::name('wy_building')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id')->select();
        $buildingIds = array();
        foreach ($buildingList as $key=>$value) {
            array_push($buildingIds,$value['value']);
            $buildingList[$key]['id']=$value['value'];
        }
        // 单元
        $unitList = Db::name('wy_unit')->where('building_id','in',$buildingIds)->where(['is_deleted'=>0])->field('id value,name label,building_id')->select();
        $unitIds = array();
        foreach ($unitList as $key=>$value) {
            array_push($unitIds,$value['value']);
            $unitList[$key]['id']=$value['value'];
        }
        // 房屋
        $housesList = Db::name('wy_houses')->where('unit_id','in',$unitIds)->where(['is_deleted'=>0])->field('id value,name label,unit_id')->select();
        // 拼装数据
        $allData = array();
        foreach ($communityList as $ck=>$cv){
            $cv['children'] = array();
            $cv['value']=$ck.'-'.$cv['value'];
            foreach ($buildingList as $bk=>$bv){
                $bv['value']=$ck.'-'.$bk.'-'.$bv['value'];
                $bv['children'] = array();
                if($bv['bd_info_id'] === $cv['id']) {
                    unset($bv['bd_info_id']);
                    foreach ($unitList as $uk=>$uv){
                        $uv['value']=$ck.'-'.$bk.'-'.$uk.'-'.$uv['value'];
                        $uv['children'] = array();
                        if($uv['building_id'] === $bv['id']) {
                            unset($uv['building_id']);
                            foreach ($housesList as $hk=>$hv){
                                if($hv['unit_id'] === $uv['id']){
                                    unset($hv['unit_id']);
                                    array_push($uv['children'],$hv);
                                }
                            }
                            if(!empty($uv['children'])) array_push($bv['children'],$uv);
                        }
                    }
                    if(!empty($bv['children'])) array_push($cv['children'],$bv);
                }
            }
            if(!empty($cv['children'])) array_push($allData,$cv);
        }
        return __success('ok',$allData);
    }

    // 获取小区楼宇单元列表
    public function getCommunityBuildingUnit(){
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->order('name ASC')->select();
        $communityIds = array();
        foreach ($communityList as $key=>$value) array_push($communityIds,$value['value']);
        // 楼宇
        $buildingList = Db::name('wy_building')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id')->order('name ASC')->select();
        $buildingIds = array();
        foreach ($buildingList as $key=>$value) array_push($buildingIds,$value['value']);
        // 单元
        $unitList = Db::name('wy_unit')->where('building_id','in',$buildingIds)->where(['is_deleted'=>0])->field('id value,name label,building_id')->order('name ASC')->select();
        // 拼装数据
        $allData = array();
        foreach ($communityList as $ck=>$cv){
            $cv['children'] = array();
            foreach ($buildingList as $bk=>$bv){
                $bv['children'] = array();
                if($bv['bd_info_id'] === $cv['value']) {
                    unset($bv['bd_info_id']);
                    foreach ($unitList as $ub=>$uv){
                        if($uv['building_id'] === $bv['value']) {
                            unset($uv['building_id']);
                            array_push($bv['children'],$uv);
                        }
                    }
                    array_push($cv['children'],$bv);
                }
            }
            if(!empty($cv['children'])) array_push($allData,$cv);
        }
        return __success('ok',$allData);
    }

    // 获取房屋未缴费账单
    public function get_house_detail_nopay() {
        $param = $this->request->post();
        $data = Db::name('wy_no_payment')->where(['house_id' => $param['id'], 'pay_status' => 0,'is_deleted'=>0])->select();
        $typetext = ['1' => '房屋', '2' => '车辆', '3' => '车位', '4' => '住户'];
        if(empty($data)) {
            return __error('暂无数据');
        } else {
            foreach($data as $k => $v) {
                $data[$k]['house_name'] = Db::name('wy_houses')->where('id', $v['house_id'])->value('name');
                $data[$k]['type'] = $typetext[$v['type'] + 1];
            }
            return __success('查询成功', $data);
        }
    }
    // $data['data'][$k]['label'] = '还没有标签';
    //            if($v['house_id'] > 0) {
    ////                $uid = Db::name('wy_house_user')->where('houses_id','=',$v['house_id'])->column('id');
    //                $hs = Db::name('wy_houses')->where('id', $v['house_id'])->field('building_id,unit_id,name,labels')->find();
    //                $bd = Db::name('wy_building')->where('id', $hs['building_id'])->value('name') ?: '';
    //                $ut = Db::name('wy_unit')->where('id', $hs['unit_id'])->value('name') ?: '';
    //                $data['data'][$k]['info'] = $data['data'][$k]['info'].$bd.'|'.$ut.'|'.$hs['name'];
    //                $data['data'][$k]['label'] = Db::name('wy_labels')->where('id',$hs['labels'])->value('name') ?: '还没有标签';
    ////                    Db::name('wy_labels_middle')->alias('m')->join('wy_labels s','s.id=m.labels_id')
    ////                    ->where('s.type_name',1)
    ////                    ->where('m.house_user_id',implode(',',$uid))->value('s.name') ?: '还没有标签';
    //            }
    //            if($v['car_area_id'] > 0) {
    //                $car_area_det = Db::name('wy_car_area')->where('id', $v['car_area_id'])->field('name,labels_id')->find();
    //                $car_area_name = $car_area_det['name'];
    //                $data['data'][$k]['info'] = $data['data'][$k]['info'].' '.$car_area_name;
    //                $data['data'][$k]['user_all_info'] = $data['data'][$k]['user_all_info'].' '.$car_area_name;
    //                $data['data'][$k]['label'] = Db::name('wy_labels')->where('id',$car_area_det['labels_id'])->value('name') ?: '还没有标签';
    ////                    Db::name('wy_labels_middle')->alias('m')->join('wy_labels s','s.id=m.labels_id')
    ////                    ->where('s.type_name',2)
    ////                    ->where('m.house_user_id',$v['house_user_id'])->value('s.name') ?: '还没有标签';
    //            }
    //            if($v['car_id'] > 0) {
    //                $car_det = Db::name('wy_car')->where('id', $v['car_id'])->field('name,labels_id')->find();
    //                $car_name = $car_det['name'];
    //                $data['data'][$k]['info'] = $data['data'][$k]['info'].' '.$car_name;
    //                $data['data'][$k]['user_all_info'] = $data['data'][$k]['user_all_info'].' '.$car_name;
    //                $data['data'][$k]['label'] = Db::name('wy_labels')->where('id',$car_det['labels_id'])->value('name') ?: '还没有标签';
    ////                    Db::name('wy_labels_middle')->alias('m')->join('wy_labels s','s.id=m.labels_id')
    ////                    ->where('s.type_name',3)
    ////                    ->where('m.house_user_id',$v['house_user_id'])->value('s.name') ?: '还没有标签';
    //            }
    //            $data['data'][$k]['house_user_list'] = [];
    //            if($v['house_user_id'] > 0) {
    //                $user = Db::name('wy_house_user')->where('id', $v['house_user_id'])->value('name');
    //                $data['data'][$k]['user_all_info'] = $data['data'][$k]['user_all_info'].' '.$user;
    //                $data['data'][$k]['house_user_text'] = $user;
    //                $data['data'][$k]['label'] = Db::name('wy_labels_middle')->alias('m')->join('wy_labels s','s.id=m.labels_id')
    //                    ->where('s.type_name',4)
    //                    ->where('m.house_user_id',$v['house_user_id'])->value('s.name') ?: '还没有标签';
    //            } else {
    //                $user=Db::name('wy_houses_user_middle')->alias('m')
    //                    ->join('wy_house_user u','u.id = m.house_user_id')
    //                    ->join('wy_houses h','m.houses_id = h.id')
    //                    ->join('wy_bd_info bd','h.bd_info_id = bd.id')
    //                    ->join('wy_building b','h.building_id = b.id')
    //                    ->join('wy_unit un','h.unit_id = un.id')
    //                    ->where('m.houses_id','=',$v['house_id'])
    //                    ->where(['m.middle_type'=>1])
    //                    ->field('u.*,bd.name bd_info_name,b.name building_name,un.name unit_name,h.name houses_name,h.id as houses_ids')
    //                    ->order('u.id','desc')->select();
    ////                $user = Db::name('wy_house_user')->where('houses_id', $v['house_id'])->field('name,phone')->select();
    //                $data['data'][$k]['house_user_list'] = $user;
    //                $data['data'][$k]['house_user_text'] = '';
    ////                $data['data'][$k]['tel'] = $user['phone'];
    //            }
}